//
//  XIAOJIEJIEViewController.swift
//  FirstSwiftProduct
//
//  Created by 范泽华 on 2017/11/8.
//  Copyright © 2017年 范泽华. All rights reserved.
//

import UIKit
import IJKMediaFramework

class XIAOJIEJIEViewController: UIViewController ,giftImageSelectDelegate{
    
    var selectIndexCount:Int!
    
    var emit : EmitView!
    func SelectDelegate(index: Int) {
        switch index {
        case 0:
            print("fas消息",index)
           
            break
        case 1:
            print("发送你爹",index)
        
//            emit.isHidden = false
            break
        case 2:
            print("礼物",index)
            selectIndexCount = selectIndexCount + 1
            
            if (selectIndexCount % 2 == 1){
                emit.isHidden = true
            }else{
                emit.isHidden = false
            }
            
            
          
            break
        case 3:
            print("奖杯",index)
            
            break
        case 4:
            print("分享",index)
         
            break
        case 5:
            print("退出",index)
            popToPUSHIN()
            break
        default:
            break
        }
    }
    
    var placeHolderView = UIImageView()
    
    public var liveHotData = livess()
    
    var urlStr : String = " "
    
    
    /** 播放器属性*/
    fileprivate lazy var options:IJKFFOptions = {
        let option = IJKFFOptions.byDefault()
        option?.setPlayerOptionIntValue(1, forKey: "videotoolbox")
        // 帧速率(fps) 非标准桢率会导致音画不同步，所以只能设定为15或者29.97
        option?.setPlayerOptionIntValue(Int64(29.97), forKey: "r")
         // 置音量大小，256为标准  要设置成两倍音量时则输入512，依此类推
        option?.setPlayerOptionIntValue(256, forKey: "vol")
        return option!
        
    }()
    
    lazy var jikVC: IJKFFMoviePlayerController = {
        //http://wvideo.spriteapp.cn/video/2016/1117/582d39fa63e2b_wpd.mp4
//        let vc = IJKFFMoviePlayerController.init(contentURLString: "http://wvideo.spriteapp.cn/video/2016/1117/582d39fa63e2b_wpd.mp4", with: self.options)
        let vc = IJKFFMoviePlayerController.init(contentURLString: self.liveHotData.stream_addr, with: self.options)
        vc?.scalingMode = IJKMPMovieScalingMode.aspectFill
        vc?.shouldAutoplay = false// 设置自动播放（设置为false, 防止自动播放, 才能更好的控制直播的状态）
        vc?.shouldShowHudView = false// 默认不显示
        DispatchQueue(label: "moviePlayer", qos: .userInitiated, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil).async {
            vc?.prepareToPlay()
        }
        return vc!
    }()
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        addObserveForMoviePlayer()
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
//        playStop()
        //移除通知
//        NotificationCenter.default.removeObserver(self)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        selectIndexCount = 0
        
        self.automaticallyAdjustsScrollViewInsets = false
        
        placeHolderView.frame = view.frame
        view.addSubview(self.placeHolderView)
        placeHolderView.setImageViewBlur(url: URL.init(string: (liveHotData.creator?.portrait)!)!, float: 0.7)
        
        
        urlStr = self.liveHotData.stream_addr
        
        view.backgroundColor = UIColor.clear
        
        self.view.insertSubview(self.jikVC.view, at: 0)
        
        popToPushVCUI()
        
        emit = EmitView.init(frame: CGRect(x: SCREEN_WIDTH - 50, y: SCRENN_HEIGHT , width: 50, height: 50))
        emit.cellArr = ["","","","","",""]
        view.addSubview(emit)
        emit.isHidden = true
        // Do any additional setup after loading the view.
    }
    
    func popToPushVCUI() -> Void {
        
        let deletBtn = UIButton.init(type: UIButtonType.custom)
        deletBtn.frame = CGRect(x: 20, y: SCRENN_HEIGHT - 60, width: 40, height: 40)
        deletBtn.setImage(UIImage.init(named: "mg_room_btn_guan_h"), for: UIControlState.normal)
        deletBtn.addTarget(self, action: #selector(popToPUSHIN), for: UIControlEvents.touchUpInside)
        
//        self.view.addSubview(deletBtn)
        
        let giftView = GiftView.init(frame: CGRect(x: 0, y: SCRENN_HEIGHT - SCREEN_WIDTH / 6, width: SCREEN_WIDTH, height: SCREEN_WIDTH / 6))
        giftView.delegate = self
        self.view.addSubview(giftView)
        
        
    }
    
    func popToPUSHIN() -> Void {
//        playStop()
        emit.isHidden = true
        self.dismiss(animated: true) {
            
        }
    }
    
    
    //页面离开后删除所有通知和方法
    public func playStop() {
        self.jikVC.shutdown()
//        self.jikVC.stop()
        removeMovieNotificationObservers()
        NotificationCenter.default.removeObserver(self)
    }
    deinit {
        print("dealloc方法被调用")
        self.playStop()
        
    }
    
    /** 释放全部通知 */
    fileprivate func removeMovieNotificationObservers() {
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.IJKMPMoviePlayerLoadStateDidChange, object: jikVC)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.IJKMPMoviePlayerPlaybackDidFinish, object: jikVC)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.IJKMPMediaPlaybackIsPreparedToPlayDidChange, object: jikVC)
        NotificationCenter.default.removeObserver(self, name: NSNotification.Name.IJKMPMoviePlayerPlaybackStateDidChange, object: jikVC)
    }
    
    /** 添加全部通知 */
    fileprivate func addObserveForMoviePlayer() {
        DispatchQueue(label: "com.nsnotifica", qos: .userInitiated, attributes: .concurrent, autoreleaseFrequency: .workItem, target: nil).async {
            NotificationCenter.default.addObserver(self, selector: #selector(self.loadStateDidChange(notification:)), name: NSNotification.Name.IJKMPMoviePlayerLoadStateDidChange, object: self.jikVC)
            
            NotificationCenter.default.addObserver(self, selector: #selector(self.moviePlayBackFinish(notification:)), name: NSNotification.Name.IJKMPMoviePlayerPlaybackDidFinish, object: self.jikVC)
            
            NotificationCenter.default.addObserver(self, selector: #selector(self.mediaIsPreparedToPlayDidChange(notification:)), name: NSNotification.Name.IJKMPMediaPlaybackIsPreparedToPlayDidChange, object: self.jikVC)
            
            NotificationCenter.default.addObserver(self, selector: #selector(self.moviePlayBackStateDidChange(notification:)), name: NSNotification.Name.IJKMPMoviePlayerPlaybackStateDidChange, object: self.jikVC)
        }
    }
    
    func loadStateDidChange(notification:NSNotification) -> Void {
        let loadState = self.jikVC.loadState as IJKMPMovieLoadState
        
        if  (loadState.rawValue & IJKMPMovieLoadState.playthroughOK.rawValue) != 0{
            //shouldAutoplay 为yes 在这种状态下会自动开始播放
            if !self.jikVC.isPlaying() {
                self.jikVC.play()
                //粒子动画开始
                emit.isHidden = false
                
                let delay = DispatchTime.now() + .seconds(1)
                DispatchQueue.main.asyncAfter(deadline: delay, execute: {
                    self.placeHolderView.removeFromSuperview()
                })
            }else if (loadState.rawValue & IJKMPMovieLoadState.stalled.rawValue) != 0 { //如果正在播放,会在此状态下暂停
                print("--此状态下暂停--：\(loadState)")
            }else {
                print("---播放开始--：\(loadState)")
            }
        }
    }
    @objc fileprivate func mediaIsPreparedToPlayDidChange(notification:Notification) {
        print("mediaIsPrepareToPlayDidChange")
    }
    
    @objc fileprivate func moviePlayBackStateDidChange(notification:Notification) {
        
        switch self.jikVC.playbackState {
            
        case IJKMPMoviePlaybackState.stopped:
            print("stopped--:\n\(self.jikVC.playbackState)")
            break
        case IJKMPMoviePlaybackState.playing:
            print("playing--:\n\(self.jikVC.playbackState)")
            break
        case IJKMPMoviePlaybackState.paused:
            print("paused--:\n\(self.jikVC.playbackState)")
            break
        case IJKMPMoviePlaybackState.interrupted:
            print("interrupted--:\n\(self.jikVC.playbackState)")
            break
        case IJKMPMoviePlaybackState.seekingForward:
            print("seekingForward--:\n\(self.jikVC.playbackState)")
            break
        case IJKMPMoviePlaybackState.seekingBackward:
            print("seekingBackward--:\n\(self.jikVC.playbackState)")
            break
            
        }
    }
    @objc fileprivate func moviePlayBackFinish(notification:Notification) {
        //播放结束时,或者是用户退出时会触发
        
        /*
         let reason = notification.userInfo?[IJKMPMoviePlayerPlaybackDidFinishReasonUserInfoKey] as! IJKMPMovieFinishReason
         switch reason {
         
         case IJKMPMovieFinishReason.playbackEnded:
         print("playbackEnded---:\n\(reason)")
         break
         case IJKMPMovieFinishReason.userExited:
         print("userExited---:\n\(reason)")
         break
         case IJKMPMovieFinishReason.playbackError:
         print("playbackError---:\n\(reason)")
         break
         }
         */
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
